<template>
  <el-dialog v-model="visible" :title="query?.title" width="1000" draggable :before-close="isClosed" :close-on-click-modal="false">
    <div :class="{ 'disabled-box': isDisabled }">
      <span @click="formData.activeIndex = 0" :class="{ 'text': true, 'active': formData.activeIndex === 0 }">普通录入</span>
      <el-divider direction="vertical" />
      <span @click="formData.activeIndex = 1" :class="{ 'text': true, 'active': formData.activeIndex === 1 }">快捷录入</span>
    </div>
    <el-divider style="margin-top: 10px" />
    <div v-if=" formData.activeIndex == 0">
      <el-form label-width="auto" :model="formData" ref="formRef" :rules="pageData.rules" :inline="true">
        <el-form-item label="供应商来源：" prop="isCommentsupplier" style="width: 46%">
          <el-radio-group v-model="pageData.isCommentsupplier">
            <el-radio v-for="(item, index) in pageData.supplierSource" :key="index" :label="item.label" :value="Number(item.value)" :disabled="isDisabled"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="pageData.isCommentsupplier == 2" label="新增供应商：" style="width: 46%">
          <el-button type="primary" @click="handleComponent('add','supplier')">新增供应商</el-button>
        </el-form-item>
        <el-form-item v-if="pageData.isCommentsupplier == 1" label="合作供应商：" prop="supplierName" style="width: 46%">
          <el-select placeholder="请选择供应商" v-model="formData.supplierName" filterable remote>
            <el-option v-for="(item, index) in supplierNames" :key="index" :label="item.label" :value="item.label" :disabled="isDisabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品来源：" prop="isCommentName" style="width: 46%">
          <el-radio-group v-model="pageData.isCommentName">
            <el-radio v-for="(item, index) in pageData.productSource" :key="index" :label="item.label" :value="Number(item.value)" :disabled="isDisabled"></el-radio>
          </el-radio-group>
        </el-form-item>    
        <el-form-item v-if="pageData.isCommentName == 2" label="商品名称：" style="width: 46%" prop="product_name">
          <el-button type="primary" @click="handleComponent('add','business')">新增业务</el-button>
        </el-form-item>
        <el-form-item v-if="pageData.isCommentName == 1" label="商品名称：" prop="product_name" style="width: 46%">
          <el-select placeholder="请选择商品" v-model="formData.product_name" filterable remote>
            <el-option v-for="(item, index) in businessNames" :key="index" :label="item.product_name" :value="String(item.product_name)" :disabled="isDisabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="牌号/款式：" style="width: 46%" prop="brand_or_style">
          <el-input placeholder="请输入商品牌号/款式" v-model="formData.brand_or_style" maxlength ="50" disabled/>
        </el-form-item>
        <el-form-item label="内部牌号：" style="width: 46%" prop="internal_brand">
          <el-input placeholder="请输入商品牌号/款式" v-model="formData.internal_brand" maxlength ="50" disabled/>
        </el-form-item>
        <el-form-item label="产品类别：" style="width: 46%" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio v-for="(item, index) in pageData.productType" :key="index" :label="item.label" :value="Number(item.value)" disabled></el-radio>
          </el-radio-group>
          <el-popover
            class="type-box"
            title="计量方式："
            placement="top-start"
            :width="400"
          >
            <el-table :data="pageData.gridData">
              <el-table-column width="70" property="productType" label="类型" />
              <el-table-column width="110" property="method" label="计量方式" />
              <el-table-column width="300" property="example" label="示例" />
            </el-table>
            <template #reference>
              <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="规格：" style="width: 46%" prop="specification">
          <el-input placeholder="请输入规格" v-model="formData.specification" disabled/>
        </el-form-item>
        <el-form-item label="计价方式：" prop="isNumOrWeight" style="width: 46%">
          <el-radio-group v-model="formData.is_quantity_based">
            <el-radio v-for="(item, index) in pageData.NumOrWeight" :key="index" :label="item.label" :value="Number(item.value)" disabled></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.is_quantity_based == 0" label="单价（按重量计）：" style="width: 46%" prop="unit_price">
          <el-input placeholder="请输入金额" v-model="formData.unit_price" style="width: 70%" disabled/>
          <el-select placeholder="单位" v-model="formData.priceUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.priceWeightUnit" :key="index" :label="item.label" :value="String(item.label)" disabled></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.is_quantity_based == 1" label="单价（按数量计）：" style="width: 46%" prop="unit_price">
          <el-input placeholder="请输入金额" v-model="formData.unit_price" style="width: 70%" disabled/>
          <el-select placeholder="单位" v-model="formData.priceUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.priceQuantityUnit" :key="index" :label="item.label" :value="String(item.label)" disabled></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品存量：" prop="stockLevel" style="width: 46%">
          <el-input v-model="stockLevel.stock" style="width: 42%;margin-left: 5px" disabled>
            <template #append>
              kg
            </template>
          </el-input>
          <el-input v-model="stockLevel.piece" style="width: 42%;margin-left: 5px" disabled>
          <template #append>
              pcs
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="理想最佳采购量：" style="width: 46%">
          <el-input-number placeholder="经济采购量" v-model="formData.idealNum" :controls="false"  disabled>
            <template #suffix>
              <span>{{ formData.is_quantity_based ==1 ? "pcs" : "kg" }}</span>
            </template>
          </el-input-number>
          <el-tooltip
          class="box-item"
          effect="dark"
          content="经济采购量需要填写订货成本与单位产品库存年维持费用率后才可显示"
          placement="bottom"
          >
            <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
        <el-divider style="margin-top: 10px" />
        <el-form-item v-if="formData.type == 1 || formData.type == 3" label="商品重量：" style="width: 46%" prop="productWeight" :error="weightQuantityError">
          <el-input placeholder="商品重量" v-model="formData.productWeight" maxlength ="50" style="width: 70%" show-word-limit/>
          <el-select placeholder="单位" v-model="formData.weightUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.weightUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.type == 2 || formData.type == 3" label="商品数量：" style="width: 46%" prop="productQuantity" :error="weightQuantityError">
          <el-input placeholder="商品数量" v-model="formData.productQuantity" maxlength ="50" style="width: 70%" show-word-limit/>
          <el-select placeholder="单位" v-model="formData.quantityUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.quantityUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总价（/元）：" style="width: 46%" prop="productSum">
          <el-input placeholder="请输入金额" v-model="formData.productSum"/>
        </el-form-item>
        <el-form-item label="采购时间：" style="width: 46%">
          <el-date-picker v-model="formData.purchaseTime" type="date" placeholder="选择时间" :size="size" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
        </el-form-item>
        <el-form-item label="商品描述：" style="width: 96%">
          <el-input placeholder="请输入内容" v-model="formData.description" type="textarea" maxlength="100" show-word-limit autosize/>
        </el-form-item>
      </el-form>
    </div>
    <div v-if=" formData.activeIndex == 1 ">
      <el-form label-width="auto" :model="formData" ref="formRef" :rules="pageData.rules" :inline="true">
        <el-form-item v-if="query?.type === 'add'" label="供应商：" prop="supplierName" style="width: 46%">
          <el-autocomplete placeholder="请输入供应商" v-model="formData.supplierName" :fetch-suggestions="querySearch" clearable/>
        </el-form-item>
        <el-form-item v-if="query?.type === 'add'" label="商品名称：" prop="product_name" style="width: 46%">
          <el-autocomplete placeholder="请输入商品名" v-model="formData.product_name" :fetch-suggestions="querySearch2" clearable/>
        </el-form-item>
        <el-form-item v-if="query?.type === 'edit'" label="供应商：" prop="supplierName" style="width: 46%">
          <el-input placeholder="请输入供应商" v-model="formData.supplierName"/>
        </el-form-item>
        <el-form-item v-if="query?.type === 'edit'" label="商品名称：" prop="product_name" style="width: 46%">
          <el-input placeholder="请输入商品名" v-model="formData.product_name"/>
        </el-form-item>
        <div class="specification-box">
          <el-form-item label="型号类别：" style="width: 96%">
            <el-radio-group v-model="formData.isSpecificationType">
              <el-radio v-for="(item, index) in pageData.specificationType" :key="index" :label="item.label" :value="Number(item.value)"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 1" v-for="item in pageData.board" :key="item.value" :label="item.label" style="width: 30%">
            <el-input-number v-model="item.data" controls-position="right">
              <template #suffix>
                <span>mm</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 2" v-for="item in pageData.pipe" :key="item.value" :label="item.label" style="width: 30%">
            <el-input-number v-model="item.data" controls-position="right">
              <template #suffix>
                <span>mm</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 3" v-for="item in pageData.stick" :key="item.value" :label="item.label" style="width:30%">
            <el-input-number v-model="item.data" controls-position="right">
              <template #suffix>
                <span>mm</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 4" v-for="item in pageData.Lens" :key="item.value" :label="item.label" style="width: 30%">
            <el-input-number v-model="item.data" controls-position="right">
              <template #suffix>
                <span>mm</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 5" v-for="item in pageData.ring" :key="item.value" :label="item.label" style="width: 30%">
            <el-input-number v-model="item.data" controls-position="right">
              <template #suffix>
                <span>mm</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 6" v-for="item in pageData.needle" :key="item.value" :label="item.label" style="width: 30%">
            <el-input-number v-model="item.data" controls-position="right">
              <template #suffix>
                <span>mm</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 7" v-for="item in specFields" :key="item.prefix" :label="item.displayName" style="width: 29%">
            <el-input v-if="item.dataType == 'string'" v-model="others[item.prefix]" @blur="handleInputBlur(item)">
              <template #prepend>
                <span>{{ item.prefix }}</span>
              </template>
            </el-input>
            <el-input-number v-if="item.dataType == 'int' || item.dataType == 'double'" v-model="others[item.prefix]" controls-position="right" @blur="handleInputBlur(item)">
              <template #prefix>
                <span>{{ item.prefix }}</span>
              </template>
            </el-input-number>
          </el-form-item>
        </div>
        <el-form-item label="牌号/款式：" style="width: 46%" prop="brand_or_style">
          <el-input placeholder="请输入商品牌号/款式" v-model="formData.brand_or_style" maxlength ="50"/>
        </el-form-item>
        <el-form-item label="内部牌号：" style="width: 46%" prop="internal_brand">
          <el-input placeholder="请输入商品牌号/款式" v-model="formData.internal_brand" maxlength ="50"/>
        </el-form-item>
        <el-form-item label="产品类别：" style="width: 46%" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio v-for="(item, index) in pageData.productType" :key="index" :label="item.label" :value="Number(item.value)"></el-radio>
          </el-radio-group>
          <el-popover
            class="type-box"
            title="计量方式："
            placement="top-start"
            :width="400"
          >
            <el-table :data="pageData.gridData">
              <el-table-column width="70" property="productType" label="类型" />
              <el-table-column width="110" property="method" label="计量方式" />
              <el-table-column width="300" property="example" label="示例" />
            </el-table>
            <template #reference>
              <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="计价方式：" prop="is_quantity_based" style="width: 46%">
          <el-radio-group v-model="formData.is_quantity_based">
            <el-radio v-for="(item, index) in pageData.NumOrWeight" :key="index" :label="item.label" :value="Number(item.value)" :disabled="is_quantity_based_disabled"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.is_quantity_based == 0" label="单价（按重量计）：" style="width: 46%" prop="unit_price">
          <el-input placeholder="请输入金额" v-model="formData.unit_price" style="width: 70%"/>
          <el-select placeholder="单位" v-model="formData.priceUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.priceWeightUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.is_quantity_based == 1" label="单价（按数量计）：" style="width: 46%" prop="unit_price">
          <el-input placeholder="请输入金额" v-model="formData.unit_price" style="width: 70%"/>
          <el-select placeholder="单位" v-model="formData.priceUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.priceQuantityUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
          </el-select>
        </el-form-item>
        <el-divider style="margin-top: 10px" />
        <el-form-item label="产品存量：" prop="stockLevel" style="width: 96%">
          <el-button type="primary" style="width: 25%" :disabled="isDisabled" @click="checkInventory">点击查看产品存量</el-button>
          <el-input v-model="stockLevel.stock" style="width: 35%;margin-left: 5px" disabled>
            <template #append>
              kg
            </template>
          </el-input>
          <el-input v-model="stockLevel.piece" style="width: 35%;margin-left: 5px" disabled>
          <template #append>
              pcs
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="formData.type == 1 || formData.type == 3" label="商品重量：" style="width: 46%" prop="productWeight" :error="weightQuantityError">
          <el-input placeholder="商品重量" v-model="formData.productWeight" maxlength ="50" style="width: 70%" show-word-limit/>
          <el-select placeholder="单位" v-model="formData.weightUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.weightUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.type == 2 || formData.type == 3" label="商品数量：" style="width: 46%" prop="productQuantity" :error="weightQuantityError">
          <el-input placeholder="商品数量" v-model="formData.productQuantity" maxlength ="50" style="width: 70%" show-word-limit/>
          <el-select placeholder="单位" v-model="formData.quantityUnit" style="width: 30%">
            <el-option v-for="(item, index) in pageData.quantityUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总价（/元）：" style="width: 46%" prop="productSum">
          <el-input placeholder="请输入金额" v-model="formData.productSum"/>
        </el-form-item>
        <el-form-item label="采购时间：" style="width: 46%">
          <el-date-picker v-model="formData.purchaseTime" type="date" placeholder="选择时间" :size="size" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
        </el-form-item>
        <el-form-item label="商品描述：" style="width: 96%">
          <el-input placeholder="请输入内容" v-model="formData.description" type="textarea" maxlength="100" show-word-limit autosize/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isClosed">取消</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading">确认</el-button>
      </div>
    </template>
    <supplierEdit :query="formQuery" :dialogVisible="dialogEditVisible" @updateData="updateData" :getAllSupplier="getAllSupplier"/>
    <businessEdit :query="businessQuery" :supplierId="supplierId" :dialogVisible="dialogbusinessVisible" @updateData="updateData" :getAllbusiness="getAllbusiness"/>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, onBeforeMount, reactive, toRefs, ref, PropType, watch, computed } from 'vue'
import { purchaseCreate, purchaseDetails, purchaseUpdate, getSupplierName, getBusinessName, purchaseInf, purchaseEoq, purchaseCreate2, getSpecificationForm, inBound, supplierHistory, productHistory } from "../service/api"
import type { ComponentSize, FormInstance, FormRules} from 'element-plus'
import { ElMessage, ElMessageBox } from "element-plus";
import supplierEdit from './supplierEdit.vue'
import businessEdit from './businessEdit.vue'
import pageData from '../service/pageService'
export default defineComponent({
    name: 'Pagination',
    components: {
        supplierEdit,
        businessEdit,
    },
    props: {
      query: {
        type: Object,
        default: () => ({})
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      getList:{
        type:Function,
        default: () => () => {}
      },
    },
    setup(props,{emit}) {
      const state = reactive({
        btnLoading: false,
        visible: false,
        dialogEditVisible: false,
        dialogbusinessVisible: false,
        formQuery: null,
        businessQuery: null,
        is_quantity_based_disabled: false,
        supplierNames:[],
        businessNames:[],
        supplierId: null,
        businessId: null,
        productId: null,
        specFields:[],//规格表
        isInitializing: true,//防止dom未加载完就初始化
        others:{},
        stockLevel:{
          stock:  null,//重量
          piece: null,//数量
        },
        formData:{
          id:null, //后端提供
          idealNum: null,
          activeIndex: 0, //0-普通录入；1-快捷录入
          type: null, //产品种类 1-原料，2-产品，3-其他
          is_quantity_based: 1, //计价是否按数量 0-按重量 1-按数量
          isSpecificationType:1, //规格类别 1-7类
          product_name: null,
          brand_or_style: null,
          internal_brand: null,
          productQuantity: null,
          productWeight: null,
          priceUnit: null, //计价单位
          weightUnit: null, //计量单位（重量）
          quantityUnit: null, //计量单位（数量）
          unit_price: null,
          productSum: null,
          description: null,
          supplierName: null,
          board:[],
          pipe:[],
          stick:[],
          Lens:[],
          ring:[],
          needle:[],
          others:{},
          purchaseTime: null, //批次采购时间
          specification: null,
        },
        simpleSupplierNames:[],
        productNames:[]
      })
      const formRef = ref<FormInstance>()
      const isClosed = () =>{
        state.visible = false
        emit('updateData', state.visible)
      }
      // 计算属性，根据 query.type 判断只读属性
      const isDisabled = computed(() => {
        return props.query?.type === "edit";
      })
       // 预先初始化 others 字段
      const initOthers = () => {
        state.others = {}
        state.formData.others = {}
      }
      const handleInputBlur = (item) =>{

      }
      // 独立验证重量和数量
      const weightQuantityError = ref('');

      const validateWeightOrQuantity = () => {
        const { productWeight, productQuantity } = state.formData;
        
        if (!productWeight && !productQuantity) {
          return '重量和数量至少填写一项';
        }
        
        return null;
      };
      // 监听重量和数量变化，实时显示错误
      watch([
        () => state.formData.productWeight,
        () => state.formData.productQuantity
      ], () => {
        weightQuantityError.value = validateWeightOrQuantity() || '';
      });
      //监听产品类别以决定计量方式
      watch(() => state.formData.type, () => {
        if(state.formData.type == 1) {
          //原料 
          state.formData.is_quantity_based = 0
          state.is_quantity_based_disabled = true
        }else if(state.formData.type == 2) {
          //产品
          state.formData.is_quantity_based = 1
          state.is_quantity_based_disabled = true
        }else {
          //其他
          state.is_quantity_based_disabled = false
        }
      })
      //监听数值补充单位
      watch(() => state.formData.is_quantity_based, () => {
        if(state.formData.is_quantity_based == 1 && state.formData.activeIndex == 1 && props.query?.type == 'add') state.formData.priceUnit = '元/pcs'
        else if(state.formData.is_quantity_based == 0 && state.formData.activeIndex == 1 && props.query?.type == 'add') state.formData.priceUnit = '元/kg'
      })
      //设置默认时间
      const getCurrentDate = () => {
        // 获取当前日期并格式化为YYYY-MM-DD
        const date = new Date()
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        state.formData.purchaseTime = `${year}-${month}-${day}`
      }
      // 封装判断isQuantityBased值的函数
      const getIsQuantityBased = (row) => {
        if( row?.type == 3 ) return 1;
        else if( row?.type == 2 ) return 0;
        else if( row?.type == 1 ) return 2;
      }
      //供应商或业务名称过滤函数
      const createFilter = (queryString: string) => {
        // 转换为小写，实现不区分大小写
        const searchText = queryString.toLowerCase()

        return (supplier: { value: string }) => {
          // 将餐厅名称转为小写，检查是否包含搜索字符串
          return supplier.value.toLowerCase().includes(searchText)
        };
      }
      //供应商名称提及函数
      const querySearch = (queryString: string, cb: any) => {
        let results = []
        console.log("queryString",queryString)
        if(queryString == null || queryString == '') results = state.simpleSupplierNames
        else if(queryString) results = state.simpleSupplierNames.filter(createFilter(queryString))
        //返回提及名称
        console.log("results",results)
        cb(results)
      }
      //产品名称提及函数
      const querySearch2 = (queryString: string, cb: any) => {
        let results = []
        if(queryString == null || queryString == '') results = state.productNames
        else if(queryString) results = state.productNames.filter(createFilter(queryString))
        //返回提及名称
        cb(results)
      }
      //单位换算（用于计算EOQ）
      const converseUnit = (row) =>{
        console.log("converseUnit",row)
        pageData.unitConversion.unitPrice = null
        pageData.unitConversion.amount = null
        pageData.unitConversion.piece = null
        if(row?.is_quantity_based == 0 && row?.priceUnit == "元/g"){
          pageData.unitConversion.unitPrice = row?.unit_price*1000
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/kg"){
          pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/T"){
          pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.is_quantity_based == 1 && row?.priceUnit == "元/pcs"){
          pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 1 && row?.priceUnit == "元/kpcs"){
          pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.totalProductWeight && row?.weightUnit == "g"){
          pageData.unitConversion.amount = row?.totalProductWeight/1000
        }else if(row?.totalProductWeight && row?.weightUnit == "kg"){
          pageData.unitConversion.amount = row?.totalProductWeight
        }else if(row?.totalProductWeight && row?.weightUnit == "T"){
          pageData.unitConversion.amount = row?.totalProductWeight*1000
        }
        if(row?.totalProductQuantity && row?.quantityUnit == "pcs"){
          pageData.unitConversion.piece = row?.totalProductQuantity
        }else if(row?.totalProductQuantity && row?.quantityUnit == "kpcs"){
          pageData.unitConversion.piece = row?.totalProductQuantity*1000
        }
        console.log("单价",pageData.unitConversion.unitPrice)
        console.log("数量",pageData.unitConversion.piece)
        console.log("重量",pageData.unitConversion.amount)
      }
      const culculateEoq = () => {
        if(state.formData.activeIndex == 0 && props.query?.supplierId && props.query?.businessId){
            purchaseEoq(props.query?.supplierId,props.query?.businessId).then((res)=>{
              console.log("eoq.res",res.data)
              converseUnit(res.data)
              if(res.data.is_quantity_based == 0 && res.data.totalFee && res.data.costRate && res.data.validityPeriod ){
                let R = res.data.costRate/100
                let D = pageData.unitConversion.amount * (12/res.data.validityPeriod)
                state.formData.idealNum = Math.round(Math.sqrt((2 * D * res.data.totalFee) / (pageData.unitConversion.unitPrice * R)));
              }else if(res.data.is_quantity_based == 1 && res.data.totalFee && res.data.costRate ){
                let R = res.data.costRate/100
                let D = pageData.unitConversion.piece * (12/res.data.validityPeriod)
                state.formData.idealNum = Math.round(Math.sqrt((2 * D * res.data.totalFee) / (pageData.unitConversion.unitPrice * R)));
              }
          })
        }else if(state.supplierId && state.businessId){
          purchaseEoq(state.supplierId,state.businessId).then((res)=>{
            console.log("eoq.res",res.data)
            converseUnit(res.data)
            if(res.data.is_quantity_based == 0 && res.data.totalFee && res.data.costRate ){
              let R = res.data.costRate/100
              state.formData.idealNum = Math.round(Math.sqrt((2 * pageData.unitConversion.amount * res.data.totalFee) / (pageData.unitConversion.unitPrice * R)));
            }else if(res.data.is_quantity_based == 1 && res.data.totalFee && res.data.costRate ){
              let R = res.data.costRate/100
              state.formData.idealNum = Math.round(Math.sqrt((2 * pageData.unitConversion.piece * 125) / (pageData.unitConversion.unitPrice * R)));
            }
          })
        }
      }
      watch(() => props.dialogVisible, () => {
        state.visible = props.dialogVisible
        state.isInitializing = true
        setTimeout(() => {
          initHistory()
        }, 600)
        initData()
        // 确保数据完全加载
        setTimeout(() => {
          state.isInitializing = false
        }, 500)
        console.log("query",props.query)
      })
      watch(() => state.formData.activeIndex, () => {
        if(state.formData.activeIndex == 0){
          getAllSupplier()
        }
      })
      //监控供应商变化从而获取对应业务
      watch(() => state.formData.supplierName, () => {
        if(props.query?.type == 'add' && state.formData.activeIndex == 0)
        {
          findSupplierIdByLabel()
          getAllbusiness()
        }
      })
      //监控业务变化从而改变回显内容
      watch(() => state.formData.product_name, () => {
        if(props.query?.type == 'add' && state.formData.activeIndex == 0)
        {
          findBusinessIdByLabel()
          purchaseInf(state.supplierId,state.businessId).then((res)=>{
            state.initsupplierName = state.formData.supplierName
            state.formData = res.data.data
            state.formData.supplierName = state.initsupplierName
            state.formData.activeIndex = 0
            getCurrentDate()
            checkInventory()
            culculateEoq()
          })
        }else if(props.query?.type == 'add' && state.formData.activeIndex == 1)
        {
          findProductIdByLabel()
          const params = {
            id:state.productId
          }
          //一旦变化，就初试化
          resetData(pageData.board)
          resetData(pageData.pipe)
          resetData(pageData.stick)
          resetData(pageData.Lens)
          resetData(pageData.ring)
          resetData(pageData.needle)
          initOthers()
          state.formData.isSpecificationType = 1
          state.formData.brand_or_style = null
          state.formData.type = 2
          state.formData.is_quantity_based = 1
          state.formData.unit_price = null
          if(state.productId){
            purchaseDetails(params).then((res)=>{
              console.log("res.data.isSpecificationType",res.data.isSpecificationType)
              state.formData.isSpecificationType = res.data.isSpecificationType
              setTimeout(() => {
                initSpecification(res)
              }, 500)
              state.formData.brand_or_style = res.data.brand_or_style
              state.formData.internal_brand = res.data.internal_brand
              state.formData.type = res.data.type
              state.formData.is_quantity_based = res.data.is_quantity_based
              state.formData.unit_price = res.data.unit_price
              state.formData.priceUnit = res.data.priceUnit
            })
          }
        }
      })
      //根据产品名初始化规格数据
      const initSpecification = (res) => {
        if(state.formData.isSpecificationType == 1)
        {
          //板类
          state.formData.board = res.data.board
          pageData.board.forEach((item, index) => {
            item.data = state.formData.board[index];
          })
        }else if(state.formData.isSpecificationType == 2)
        {
          //管类
          state.formData.pipe = res.data.pipe
          pageData.pipe.forEach((item, index) => {
            item.data = state.formData.pipe[index];
          })
        }else if(state.formData.isSpecificationType == 3)
        {
          //棒类
          state.formData.stick = res.data.stick
          pageData.stick.forEach((item, index) => {
            item.data = state.formData.stick[index];
          })
        }else if(state.formData.isSpecificationType == 4)
        {
          //镜类
          state.formData.Lens = res.data.Lens
          pageData.Lens.forEach((item, index) => {
            item.data = state.formData.Lens[index];
          })
        }else if(state.formData.isSpecificationType == 5)
        {
          //环类
          state.formData.ring = res.data.ring
          pageData.ring.forEach((item, index) => {
            item.data = state.formData.ring[index];
          })
        }else if(state.formData.isSpecificationType == 6)
        {
          //点焊针类
          state.formData.needle = res.data.needle
          pageData.needle.forEach((item, index) => {
            item.data = state.formData.needle[index];
          })
        }
        else if(state.formData.isSpecificationType == 7)
        {
          //其他类
          state.formData.others = res.data.others
          state.others = state.formData.others
        }
      }
      //监控总价变化
      watch(
        [
          () => state.formData.is_quantity_based,
          () => state.formData.productQuantity,
          () => state.formData.productWeight,
          () => state.formData.unit_price,
          () => state.formData.priceUnit,
          () => state.formData.weightUnit,
          () => state.formData.quantityUnit,
        ],
        (newValues, oldValues) => {
        converseUnit2(state.formData)
        if(state.formData.is_quantity_based == 1) state.formData.productSum = +(pageData.unitConversion.unitPrice * pageData.unitConversion.piece).toFixed(2);
        else if(state.formData.is_quantity_based == 0) state.formData.productSum = +(pageData.unitConversion.unitPrice*pageData.unitConversion.amount).toFixed(2);
      })
      //监控外部牌号改内部牌号
      watch(() => state.formData.brand_or_style, () => {
        if(state.formData.activeIndex == 1) state.formData.internal_brand = state.formData.brand_or_style
      })
      //监控产品规格类型初始化
      watch(() => state.formData.isSpecificationType, () => {
        if(!state.isInitializing && state.formData.activeIndex == 1) {
          resetData(pageData.board)
          resetData(pageData.pipe)
          resetData(pageData.stick)
          resetData(pageData.Lens)
          resetData(pageData.ring)
          resetData(pageData.needle)
          initOthers()
        }
      })
      //根据供应商名字找到对应的供应商id
      const findSupplierIdByLabel = () => {
        if(props.query?.type == 'add') state.supplierId = state.supplierNames.find(supplier => supplier.label === state.formData.supplierName)?.supplierId
      }
      //根据业务名字找到对应的业务id
      const findBusinessIdByLabel = () => {
        if(props.query?.type == 'add') state.businessId = state.businessNames.find(business => business.product_name === state.formData.product_name)?.id
      }
      //根据产品名字找到对应的产品id
      const findProductIdByLabel = () => {
        if(props.query?.type == 'add') state.productId = state.productNames.find(product => product.value === state.formData.product_name)?.id
      }
      //新建供应商后刷新供应商
      const getAllSupplier = () => {
        getSupplierName().then((res)=>{
          state.supplierNames = res.data.data
        })
      }
      //新建业务后刷新业务
      const getAllbusiness = () => {
        getBusinessName(state.supplierId).then((res)=>{
          state.businessNames = res.data.data
        })
      }
      //初始化数组函数
      const resetData = (arr) => {
        arr.forEach(item => {
          item.data = null
        })
      }
      //初始化供应商历史和产品历史数据函数
      const initHistory = () => {
        if(props.query?.type == 'add' && state.formData.activeIndex == 1) {
          supplierHistory().then((res)=>{
            state.simpleSupplierNames = res.data.data
          })
          productHistory().then((res)=>{
            state.productNames = res.data.data
          })
        }
      }
      const initData = () => {
        console.log("props.query",props.query)
        state.stockLevel = JSON.parse(JSON.stringify(pageData.initStockLevel))
        getSpecificationForm().then((res)=>{
          state.specFields = res.data.data
          console.log("规格表",state.specFields)
        })
        //初始化表单
        pageData.isCommentsupplier = 1
        pageData.isCommentName = 1
        state.formData = JSON.parse(JSON.stringify(pageData.initPurchase))
        resetData(pageData.board)
        resetData(pageData.pipe)
        resetData(pageData.stick)
        resetData(pageData.Lens)
        resetData(pageData.ring)
        resetData(pageData.needle)
        initOthers()
        state.formData.quantityUnit = "pcs"
        state.formData.weightUnit = "kg"
        if(state.formData.activeIndex == 0){
          getAllSupplier()
        }
        if(props.query?.type == 'add') { 
          state.isInitializing = false 
          getCurrentDate()
        }
        if(props.query?.type == 'edit' || props.query?.type == 'view') {
          const params = {
            id:props.query?.id
          }
          purchaseDetails(params).then((res)=>{
            console.log('res',res)
            state.formData = res.data
            if(state.formData.isSpecificationType == 1)
            {
              //板类
              pageData.board.forEach((item, index) => {
                item.data = state.formData.board[index];
              })
            }else if(state.formData.isSpecificationType == 2)
            {
              //管类
              pageData.pipe.forEach((item, index) => {
                item.data = state.formData.pipe[index];
              })
            }else if(state.formData.isSpecificationType == 3)
            {
              //棒类
              pageData.stick.forEach((item, index) => {
                item.data = state.formData.stick[index];
              })
            }else if(state.formData.isSpecificationType == 4)
            {
              //镜类
              pageData.Lens.forEach((item, index) => {
                item.data = state.formData.Lens[index];
              })
            }else if(state.formData.isSpecificationType == 5)
            {
              //环类
              pageData.ring.forEach((item, index) => {
                item.data = state.formData.ring[index];
              })
            }else if(state.formData.isSpecificationType == 6)
            {
              //点焊针类
              pageData.needle.forEach((item, index) => {
                item.data = state.formData.needle[index];
              })
            }
            else if(state.formData.isSpecificationType == 7)
            {
              //其他类
              state.others = state.formData.others
            }
            checkInventory()
            culculateEoq()
          }).catch((error) => {
            console.error('无法获取数据', error);
          });
        }
      }
      const handleComponent = (val , category) => {
        if(val == "add" && category == "supplier")
        {
          const data = {
            type:val,
            title:"供应商档案登记表"
          }
          state.formQuery = data
          state.dialogEditVisible = true
        }
        else if(val == "add" && category == "business")
        {
          const data = {
            type:val,
            title:"新增业务"
          }
          state.businessQuery = data
          state.dialogbusinessVisible = true
        }
      }
      const updateData = (val) =>{
        state.dialogEditVisible = val
        state.dialogbusinessVisible = val
      }
      //单位换算(用于计算总价)
      const converseUnit2 = (row) =>{
          console.log("converseUnit",row)
        pageData.unitConversion.unitPrice = null
        pageData.unitConversion.amount = null
        pageData.unitConversion.piece = null
        if(row?.is_quantity_based == 0 && row?.priceUnit == "元/g"){
          pageData.unitConversion.unitPrice = row?.unit_price*1000
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/kg"){
          pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/T"){
          pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.is_quantity_based == 1 && row?.priceUnit == "元/pcs"){
          pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 1 && row?.priceUnit == "元/kpcs"){
          pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.productWeight && row?.weightUnit == "g"){
          pageData.unitConversion.amount = row?.productWeight/1000
        }else if(row?.productWeight && row?.weightUnit == "kg"){
          pageData.unitConversion.amount = row?.productWeight
        }else if(row?.productWeight && row?.weightUnit == "T"){
          pageData.unitConversion.amount = row?.productWeight*1000
        }
        if(row?.productQuantity && row?.quantityUnit == "pcs"){
          pageData.unitConversion.piece = row?.productQuantity
        }else if(row?.productQuantity && row?.quantityUnit == "kpcs"){
          pageData.unitConversion.piece = row?.productQuantity*1000
        }
        console.log("pageData.unitConversion.unitPrice",pageData.unitConversion.unitPrice)
      }
      const checkInventory = () => {
        if(!state.formData.product_name) ElMessage.warning("请先填写产品名称！")
        // else if(!state.formData.brand_or_style) ElMessage.warning("请先填写产品外部牌号或款式！")
        // else if(!state.formData.internal_brand) ElMessage.warning("请先填写产品内部牌号或款式！")
        else if(!state.formData.unit_price) ElMessage.warning("请先填写产品的单价")
        else if(!state.formData.type) ElMessage.warning("请先填写产品的类型")
        else if(state.formData.is_quantity_based == null || state.formData.is_quantity_based == undefined) ElMessage.warning("请先填写产品的计价方式")
        else {
          specificationConversion()
          console.log("specification",state.formData.specification)
          converseUnit2(state.formData)
          let isQuantityBased = getIsQuantityBased(state.formData)
          const inBoundData = {
            skuName: state.formData.product_name,
            skuBrand: state.formData.brand_or_style?? "",
            internalBrand: state.formData.internal_brand?? "",
            specification: state.formData?.specification ?? "",
            unitPrice: pageData.unitConversion.unitPrice,
            byQuantity: isQuantityBased,
          }
          inBound(inBoundData).then((res)=>{
            state.stockLevel.stock= res.data.data.stock
            state.stockLevel.piece= res.data.data.piece
            console.log("inBoundData",res)
          })
        }
      }
      const specificationConversion = () => {
        if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 1 && pageData.board.every(item => item.data)) {
          state.formData.board = pageData.board.map(item => item.data)
          state.formData.specification = "L"+state.formData.board[0]+"*"+"W"+state.formData.board[1]+"*"+"T"+state.formData.board[2]
          state.formData.boardJson = JSON.stringify(state.formData.board)
        }
        else if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 2 && pageData.pipe.every(item => item.data)){
          state.formData.pipe = pageData.pipe.map(item => item.data)
          state.formData.specification = "D"+state.formData.pipe[1]+"*"+"d"+state.formData.pipe[2]+"*"+"L"+state.formData.pipe[0]
          state.formData.pipeJson = JSON.stringify(state.formData.pipe)
        }
        else if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 3 && pageData.stick.every(item => item.data)){
          state.formData.stick = pageData.stick.map(item => item.data)
          state.formData.specification = "D"+state.formData.stick[1]+"*"+"L"+state.formData.stick[0]
          state.formData.stickJson = JSON.stringify(state.formData.stick)
        } 
        else if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 4 && pageData.Lens.every(item => item.data)){
          state.formData.Lens = pageData.Lens.map(item => item.data)
          state.formData.specification = "D"+state.formData.Lens[0]+"*"+"W"+state.formData.Lens[1]
          state.formData.LensJson = JSON.stringify(state.formData.Lens)
        } 
        else if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 5 && pageData.ring.every(item => item.data)){
          state.formData.ring = pageData.ring.map(item => item.data)
          state.formData.specification = "D"+state.formData.ring[0]+"*"+"d"+state.formData.ring[1]
          state.formData.ringJson = JSON.stringify(state.formData.ring)
        } 
        else if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 6 && pageData.needle.every(item => item.data)){
          state.formData.needle = pageData.needle.map(item => item.data)
          state.formData.specification = "L"+state.formData.needle[0]+"*"+"D"+state.formData.needle[1]+"*"+"Φ"+state.formData.needle[2]
          state.formData.needleJson = JSON.stringify(state.formData.needle)
        }
        else if(state.formData.activeIndex == 1 && state.formData.isSpecificationType == 7 && Object.keys(state.others).length > 0){
          console.log("state.others",state.others)
          state.formData.others = state.others
          state.formData.specification = ''
          Object.keys(state.formData.others).forEach(prefix => {
            // 检查属性是否为自有属性且值不为空
            if (state.formData.others.hasOwnProperty(prefix) && state.formData.others[prefix]) {
              // 将前缀和值组合，并用 * 连接
              state.formData.specification =  state.formData.specification + `${prefix}${state.formData.others[prefix]}` + "*"
            }
          })
          state.formData.specification = state.formData.specification.slice(0, -1)
        }else if (state.formData.activeIndex == 1){
          state.formData.specification = null
        }
      }
      const submit = () => {
        specificationConversion()
        console.log("state.formData",state.formData)
        const error = validateWeightOrQuantity();
        if (error) {
          weightQuantityError.value = validateWeightOrQuantity() || '';
          ElMessage.error(error);
          return;
        }
        formRef.value.validate((valid) => {
          console.log("valid",valid)
          if (valid) { 
            // 验证通过
            state.btnLoading = true
            if(props.query.type == 'edit'){
              purchaseUpdate(props.query?.id,state.formData).then((res)=>{
                ElMessage.success("保存成功！")
                props.getList()
                isClosed(); // 关闭弹窗
                state.btnLoading = false
              })
            }else if(props.query.type == 'add' && state.formData.activeIndex == 0){
              purchaseCreate2(state.supplierId,state.businessId,state.formData).then((res)=>{
                ElMessage.success("保存成功！")
                props.getList()
                isClosed(); // 关闭弹窗
                state.btnLoading = false
              })
            }else if(props.query.type == 'add' && state.formData.activeIndex == 1){
              purchaseCreate(state.formData).then((res)=>{
                ElMessage.success("保存成功！")
                props.getList()
                isClosed(); // 关闭弹窗
                state.btnLoading = false
              })
            }
          }else {
            ElMessage.error('请完成必填字段')
          }
        })
      }
      onBeforeMount(() => {
        console.log("way",state.way)
      })
      return {
        ...toRefs(state),
        isClosed,
        formRef,
        pageData,
        submit,
        handleComponent,
        updateData,
        isDisabled,
        getAllbusiness,
        getAllSupplier,
        handleInputBlur,
        checkInventory,
        weightQuantityError,
        querySearch,
        querySearch2
      }
    }
})
</script>
<style scoped>
.layout{
  width: auto;
  height: 800px;
  background-color: #FFFFFF;
}

.text {
  font-size: 16px;
  color: #6c757d;; /* 默认字体颜色 */
}

/* 鼠标悬浮时的样式 */
.text:hover {
  color: #212529;
  font-weight: bold;
  background-color: #f0f8ff;
}

/* 鼠标点击时的样式 */
.active {
  cursor: pointer;
  color: #212529;
  font-weight: bold;
  font-size: 24px;
}

.specification-box {
  background-color: #f5f7fa;
  margin-bottom: 10px;
  max-height: 150px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示竖向滚动条 */
}

.disabled-box {
  cursor: not-allowed;
  pointer-events: none; /* 阻止点击事件 */
}
</style>
  